package com.lyx.user.service.impl;

import com.jx.sms.config.SmsType;
import com.jx.sms.core.SmsSendManager;
import com.jx.sms.core.entity.SmsResponse;
import com.jx.sms.core.entity.SmsSend;
import com.lyx.common.exception.BusinessException;
import com.lyx.common.exception.ExceptionEnum;
import com.lyx.user.service.SmsService;
import com.lyx.common.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author 14667
 * @date 2022/7/18 18:51
 */
@Component
public class SmsServiceImpl implements SmsService {

    @Autowired
    SmsSendManager sendManager;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Value("${smsCode.length}")
    private Integer codeLen;
    @Override
    public boolean send(String phone) {
        String code = redisTemplate.opsForValue().get("phone");
        if(!StringUtils.isEmpty(code)){
            //TODO 抛出异常，请勿重复发送
            throw new BusinessException(ExceptionEnum.TOO_FAST);
        }
        SmsSend smsSend = new SmsSend();
        List<String> phones = new ArrayList<>();
        phones.add(phone);
        smsSend.setPhones(phones);
        smsSend.setType(SmsType.notice);
        code = VerifyCodeUtils.generateNum(codeLen);
        smsSend.setContent(code);
        SmsResponse response = sendManager.send(smsSend);
        if(response.getCode().equals("0")){
            redisTemplate.opsForValue().set(phone,code, 5,TimeUnit.MINUTES);
            return true;
        }
        return false;
    }
}
